package download

import (
	"fmt"
	"server/dao"
	"server/models"
	"strings"
)

// type Res struct {
// 	List  []*models.AdminUser
// 	Count int64
// }

func Create(doc models.AdminDownload) (*models.AdminDownload, error) {
	err := dao.DB.Create(&doc).Error
	if err != nil {
		return nil, err
	}
	return &doc, nil
}

type Res struct {
	List  []*models.AdminDownload
	Count int64
}

func GetList(page int64, perPage int64, name string) (Res, error) {
	var res Res
	// 查询条件
	whereStr := []string{"status >= 0"}
	if name != "" {
		whereStr = append(whereStr, " AND name LIKE '%"+name+"%'")
	}
	whereStrLong := strings.Join(whereStr, "")

	// 分页查询
	errFind := dao.DB.Model(&models.AdminDownload{}).Select([]string{"id", "name", "url", "user_id", "status", "created_time", "updated_time"}).Where(whereStrLong).Offset(int(perPage * (page - 1))).Limit(int(perPage)).Preload("User").Find(&res.List).Error
	if errFind != nil {
		return res, errFind
	}

	errCount := dao.DB.Model(&models.AdminDownload{}).Where(whereStrLong).Count(&res.Count).Error
	if errCount != nil {
		return res, errCount
	}
	fmt.Printf("res: %#v\n", res)
	return res, nil
}
